package br.com.gip.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import br.com.gip.business.AnaliseImpactoBusiness;
import br.com.gip.business.ArtefatoBusiness;
import br.com.gip.business.ProjetoBusiness;
import br.com.gip.constant.TipoManutencao;
import br.com.gip.repository.model.Artefato;
import br.com.gip.repository.model.Projeto;
import br.com.gip.service.JasperUtil;

@Scope("session")
@Controller("relatorioController")
public class RelatorioController implements Serializable {

	private static final long serialVersionUID = 6730771005645979890L;

	@Autowired
	private ProjetoBusiness projetoBusiness;

	@Autowired
	private ArtefatoBusiness artefatoBusiness;

	@Autowired
	private AnaliseImpactoBusiness analiseImpactoBusiness;
	
	private Long projetoId;
	
	private Artefato artefato;
	
	private Artefato artefatoFilter;
	
	private TipoManutencao tipoManutencao;
	
	private List<Artefato> impactos;
	
	public RelatorioController() {
		this.reset();
	}
	
	public String analiseImpacto() {
		this.reset();
		return "relatorio-analise-impacto";
	}
	
	public String analisarImpacto() {
		this.impactos = this.analiseImpactoBusiness.analisarImpacto(this.artefato);
		return "relatorio-analise-impacto";
	}
	
	@SuppressWarnings("deprecation")
	public void gerarPdf() throws JRException, IOException {
		FacesContext facesContext = FacesContext.getCurrentInstance();  
		HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();  
		HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();  

		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("PATH_LOGO_UFSCAR", request.getRealPath("/image/gip-home.jpg"));
		parameters.put("PATH_LOGO_GIP", request.getRealPath("/image/ufscar-home.gif"));
		parameters.put("TIPO_MANUTENCAO", this.tipoManutencao.getDescricao());
		
		JRBeanCollectionDataSource artefatos = new JRBeanCollectionDataSource(JasperUtil.converterArtefatos(this.getImpactos()));
		JasperPrint report = JasperFillManager.fillReport(request.getRealPath("/report/analise-impacto.jasper"), parameters, artefatos);
		
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		JasperExportManager.exportReportToPdfStream(report, output);
		
		Date dataAtual = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
		String pdfName = "analise-impacto-" + dateFormat.format(dataAtual) + ".pdf";

		response.setHeader("Content-type", "application/pdf");
		response.setHeader("Content-disposition", "attachment; filename=" + pdfName + ";");
		response.setContentLength(output.size());  

		ServletOutputStream flusher = response.getOutputStream();  
		output.writeTo(flusher);   
		
		flusher.flush();  
		flusher.close();  
		
		FacesContext.getCurrentInstance().responseComplete();  
		output.close();   
	}
	
	public SelectItem[] getAllProjetos() {
		List<SelectItem> itens = new ArrayList<SelectItem>();
		itens.add(new SelectItem("", "Selecione"));

		for (Projeto projeto : this.projetoBusiness.buscarProjetos()) {
			itens.add(new SelectItem(projeto.getProjetoId(), projeto.getNome()));
		}

		return itens.toArray(new SelectItem[itens.size()]);
	}

	public SelectItem[] getAllArtefatos() {
		List<SelectItem> itens = new ArrayList<SelectItem>();
		itens.add(new SelectItem("", "Selecione"));

		if (this.projetoId != null) {
			for (Artefato artefato : this.artefatoBusiness.buscarArtefatos(null, this.projetoId, null)) {
				itens.add(new SelectItem(artefato.getArtefatoId(), artefato.getNome()));
			}
		}

		return itens.toArray(new SelectItem[itens.size()]);
	}

	public SelectItem[] getAllTiposManutencoes() {
		List<SelectItem> itens = new ArrayList<SelectItem>();
		itens.add(new SelectItem("", "Selecione"));

		for (TipoManutencao tipoManutencao : TipoManutencao.values()) {
			itens.add(new SelectItem(tipoManutencao.name(), tipoManutencao.getDescricao()));
		}

		return itens.toArray(new SelectItem[itens.size()]);
	}
	
	private void reset() {
		this.projetoId = null;
		this.tipoManutencao = null;
		this.artefato = new Artefato();
		this.artefatoFilter = new Artefato();
		this.impactos = new ArrayList<Artefato>();
	}
	
	public Long getProjetoId() {
		return projetoId;
	}

	public void setProjetoId(Long projetoId) {
		this.projetoId = projetoId;
	}
	
	public Artefato getArtefato() {
		return artefato;
	}

	public void setArtefato(Artefato artefato) {
		this.artefato = artefato;
	}

	public Artefato getArtefatoFilter() {
		return artefatoFilter;
	}

	public void setArtefatoFilter(Artefato artefatoFilter) {
		this.artefatoFilter = artefatoFilter;
	}

	public TipoManutencao getTipoManutencao() {
		return tipoManutencao;
	}

	public void setTipoManutencao(TipoManutencao tipoManutencao) {
		this.tipoManutencao = tipoManutencao;
	}

	public List<Artefato> getImpactos() {
//		List<Artefato> artefatos = new ArrayList<Artefato>();
//		
//		System.out.println(artefatoFilter.getNome());
//		
//		for (Artefato a : this.impactos) {
//			if ((StringUtils.isBlank(artefatoFilter.getNome()) || StringUtils.equals(artefatoFilter.getNome(), a.getNome())) && 
//					(StringUtils.isBlank(artefatoFilter.getProjeto().getNome()) || StringUtils.equals(artefatoFilter.getProjeto().getNome(), a.getProjeto().getNome())) && 
//						(StringUtils.isBlank(artefatoFilter.getCategoria().getNome()) || StringUtils.equals(artefatoFilter.getCategoria().getNome(), a.getCategoria().getNome()))) {
//				artefatos.add(a);
//			}
//		}
//		
//		return artefatos;
		return this.impactos;
	}

	public void setImpactos(List<Artefato> impactos) {
		this.impactos = impactos;
	}
	
}
